package com.cmeduSystem.webadmin.app.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.cmeduSystem.common.log.annotation.OperationLog;
import com.cmeduSystem.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.cmeduSystem.webadmin.app.vo.*;
import com.cmeduSystem.webadmin.app.dto.*;
import com.cmeduSystem.webadmin.app.model.*;
import com.cmeduSystem.webadmin.app.service.*;
import com.cmeduSystem.common.core.object.*;
import com.cmeduSystem.common.core.util.*;
import com.cmeduSystem.common.core.constant.*;
import com.cmeduSystem.common.core.annotation.MyRequestBody;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 工单类型操作控制器类。
 *
 * @author xulei
 * @date 2025-09-04
 */
@Tag(name = "工单类型管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/ticketBusinessType")
public class TicketBusinessTypeController {

    @Autowired
    private TicketBusinessTypeService ticketBusinessTypeService;

    /**
     * 新增工单类型数据。
     *
     * @param ticketBusinessTypeDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"ticketBusinessTypeDto.id"})
    @SaCheckPermission("ticketBusinessType.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TicketBusinessTypeDto ticketBusinessTypeDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(ticketBusinessTypeDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TicketBusinessType ticketBusinessType = MyModelUtil.copyTo(ticketBusinessTypeDto, TicketBusinessType.class);
        // 验证父Id的数据合法性
        TicketBusinessType parentTicketBusinessType;
        if (MyCommonUtil.isNotBlankOrNull(ticketBusinessType.getParentId())) {
            parentTicketBusinessType = ticketBusinessTypeService.getById(ticketBusinessType.getParentId());
            if (parentTicketBusinessType == null) {
                errorMessage = "数据验证失败，关联的父节点并不存在，请刷新后重试！";
                return ResponseResult.error(ErrorCodeEnum.DATA_PARENT_ID_NOT_EXIST, errorMessage);
            }
        }
        ticketBusinessType = ticketBusinessTypeService.saveNew(ticketBusinessType);
        return ResponseResult.success(ticketBusinessType.getId());
    }

    /**
     * 更新工单类型数据。
     *
     * @param ticketBusinessTypeDto 更新对象。
     * @return 应答结果对象。
     */
    @SaCheckPermission("ticketBusinessType.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody TicketBusinessTypeDto ticketBusinessTypeDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(ticketBusinessTypeDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TicketBusinessType ticketBusinessType = MyModelUtil.copyTo(ticketBusinessTypeDto, TicketBusinessType.class);
        TicketBusinessType originalTicketBusinessType = ticketBusinessTypeService.getById(ticketBusinessType.getId());
        if (originalTicketBusinessType == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 验证父Id的数据合法性
        if (MyCommonUtil.isNotBlankOrNull(ticketBusinessType.getParentId())
                && ObjectUtil.notEqual(ticketBusinessType.getParentId(), originalTicketBusinessType.getParentId())) {
            TicketBusinessType parentTicketBusinessType = ticketBusinessTypeService.getById(ticketBusinessType.getParentId());
            if (parentTicketBusinessType == null) {
                // NOTE: 修改下面方括号中的话述
                errorMessage = "数据验证失败，关联的 [父节点] 并不存在，请刷新后重试！";
                return ResponseResult.error(ErrorCodeEnum.DATA_PARENT_ID_NOT_EXIST, errorMessage);
            }
        }
        if (!ticketBusinessTypeService.update(ticketBusinessType, originalTicketBusinessType)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除工单类型数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("ticketBusinessType.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除工单类型数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("ticketBusinessType.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的工单类型列表。
     *
     * @param ticketBusinessTypeDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("ticketBusinessType.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<TicketBusinessTypeVo>> list(
            @MyRequestBody TicketBusinessTypeDto ticketBusinessTypeDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        TicketBusinessType ticketBusinessTypeFilter = MyModelUtil.copyTo(ticketBusinessTypeDtoFilter, TicketBusinessType.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TicketBusinessType.class);
        List<TicketBusinessType> ticketBusinessTypeList =
                ticketBusinessTypeService.getTicketBusinessTypeListWithRelation(ticketBusinessTypeFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(ticketBusinessTypeList, TicketBusinessTypeVo.class));
    }

    /**
     * 查看指定工单类型对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("ticketBusinessType.view")
    @GetMapping("/view")
    public ResponseResult<TicketBusinessTypeVo> view(@RequestParam Long id) {
        TicketBusinessType ticketBusinessType = ticketBusinessTypeService.getByIdWithRelation(id, MyRelationParam.full());
        if (ticketBusinessType == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TicketBusinessTypeVo ticketBusinessTypeVo = MyModelUtil.copyTo(ticketBusinessType, TicketBusinessTypeVo.class);
        return ResponseResult.success(ticketBusinessTypeVo);
    }

    /**
     * 以字典形式返回全部工单类型数据集合。字典的键值为[id, typeName]。
     * 白名单接口，登录用户均可访问。
     *
     * @param filter 过滤对象。
     * @return 应答结果对象，包含的数据为 List<Map<String, String>>，map中包含两条记录，key的值分别是id和name，value对应具体数据。
     */
    @GetMapping("/listDict")
    public ResponseResult<List<Map<String, Object>>> listDict(@ParameterObject TicketBusinessTypeDto filter) {
        List<TicketBusinessType> resultList =
                ticketBusinessTypeService.getListByFilter(MyModelUtil.copyTo(filter, TicketBusinessType.class));
        return ResponseResult.success(MyCommonUtil.toDictDataList(
                resultList,
                TicketBusinessType::getId,
                TicketBusinessType::getTypeName,
                TicketBusinessType::getParentId,
                Comparator.comparing(TicketBusinessType::getSort), true));
    }

    /**
     * 根据字典Id集合，获取查询后的字典数据。
     *
     * @param dictIds 字典Id集合。
     * @return 应答结果对象，包含字典形式的数据集合。
     */
    @GetMapping("/listDictByIds")
    public ResponseResult<List<Map<String, Object>>> listDictByIds(@RequestParam List<Long> dictIds) {
        List<TicketBusinessType> resultList = ticketBusinessTypeService.getInList(new HashSet<>(dictIds));
        return ResponseResult.success(MyCommonUtil.toDictDataList(
                resultList, TicketBusinessType::getId, TicketBusinessType::getTypeName, TicketBusinessType::getParentId));
    }

    /**
     * 根据父主键Id，以字典的形式返回其下级数据列表。
     * 白名单接口，登录用户均可访问。
     *
     * @param parentId 父主键Id。
     * @return 按照字典的形式返回下级数据列表。
     */
    @GetMapping("/listDictByParentId")
    public ResponseResult<List<Map<String, Object>>> listDictByParentId(@RequestParam(required = false) Long parentId) {
        List<TicketBusinessType> resultList = ticketBusinessTypeService.getListByParentId("parentId", parentId);
        return ResponseResult.success(MyCommonUtil.toDictDataList(
                resultList,
                TicketBusinessType::getId,
                TicketBusinessType::getTypeName,
                TicketBusinessType::getParentId,
                Comparator.comparing(TicketBusinessType::getSort), true));
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        TicketBusinessType originalTicketBusinessType = ticketBusinessTypeService.getById(id);
        if (originalTicketBusinessType == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (ticketBusinessTypeService.hasChildren(id)) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象存在子对象] ，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.HAS_CHILDREN_DATA, errorMessage);
        }
        if (!ticketBusinessTypeService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
